import {
    coreAppConfigDetail,
    coreAppConfigDetailUnlogin,
    coreAppList
} from '@/apis/core/app'
import { CORE_APP_LIST } from '@/config/constant'
import { ICoreAppPinia } from '@/types/core/app'
import { createDiscreteApi } from 'naive-ui'
import { defineStore } from 'pinia'
import { useAuthUserStore } from '../auth/user'

const { message } = createDiscreteApi(['message'])
export const useCoreAppStore = defineStore('coreApp', {
    state: (): ICoreAppPinia => ({
        list: localStorage.getItem(CORE_APP_LIST)
            ? JSON.parse(localStorage.getItem(CORE_APP_LIST) || '')
            : [],
        config: null as any
    }),
    actions: {
        async getConfig(force = false) {
            if (force || !this.config) {
                try {
                    const userStore = useAuthUserStore()
                    const API = userStore.isLoggedIn
                        ? coreAppConfigDetail
                        : coreAppConfigDetailUnlogin

                    const res = await API({
                        app_id: import.meta.env.VITE_APP_ID
                    })
                    this.config = res
                    return { ...res }
                } catch (error) {
                    message.error((error as Error).message)
                    return {}
                }
            }

            return this.config
        },
        async getList(force = false) {
            if (!force && this.list.length) {
                return this.list
            }

            const res = await coreAppList()
            localStorage.setItem(CORE_APP_LIST, JSON.stringify(res))
            this.list = res
            return [...res]
        }
    }
})
